<template>
  <div>
    <el-card class="couponCard">
      <template #header>
        <div style="font-size: 30px; font-weight: 900">設置禮金券</div>
      </template>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="中文禮金券名稱" prop="nameCn">
          <el-input v-model="form.nameCn" class="input-width" />
        </el-form-item>
        <el-form-item label="英文禮金券名稱" prop="nameEn">
          <el-input v-model="form.nameEn" class="input-width" />
        </el-form-item>
        <el-form-item label="金額">
          <el-input-number
            v-model.number="form.amount"
            :min="0"
            :max="999999"
            controls-position="right"
            class="input-width"
          />
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="form.startTime"
            placeholder="選擇日期"
            type="datetime"
            :default-time="form.startTime"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
          至
          <el-date-picker
            v-model="form.endTime"
            placeholder="選擇日期"
            type="datetime"
            :default-time="form.endTime"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="備註">
          <el-input v-model="form.note" :rows="1" type="textarea" style="width: 220px;" />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="selectProduct"
            filterable
            remote
            reserve-keyword
            placeholder="商品名称/商品货号"
            :remote-method="searchProductMethod"
            :loading="selectProductLoading"
          >
            <el-option
              v-for="item in selectProductOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            >
              <span style="float: left">{{ item.productName }}</span>
              <!--                  <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.productSn }}</span>-->
            </el-option>
          </el-select>
          <el-button @click="handleAddProductRelation()">添加</el-button>
          <el-table
            ref="productRelationTable"
            :data="productList"
            style="width: 100%;margin-top: 20px"
            border
            stripe
          >
            <el-table-column label="商品名称"      >
              <template slot-scope="scope">{{ scope.row.productName }}</template>
            </el-table-column>
            <!--                <el-table-column label="货号"       width="120">-->
            <!--                  <template slot-scope="scope">NO.{{ scope.row.productSn }}</template>-->
            <!--                </el-table-column>-->
            <el-table-column label="操作"       width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDeleteProductRelation(scope.$index, scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button v-if="!isEdit" @click="resetForm('form')">重置</el-button>
        <el-button type="primary" @click="onSubmit('form')">提交</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getTree } from '@/api/pms/productCategory'
import { getProduct } from '@/api/pms/product'
import { add, edit, getOne } from '@/api/sms/coupon'
import { setTitle } from '@/utils'

const defaultCoupon = {
  nameCn: null, // 中文
  nameEn: null, // 英文
  amount: null, // 禮金券金額
  startTime: null, // 開始時間
  endTime: null, // 結束時間
  note: '', // 備註
  productIds: [], // 可使用禮金券商品id
  couponType: 1,
  useType: 2
}

export default {
  name: 'AddGiftCard',
  components: {},
  data() {
    return {
      form: Object.assign({}, defaultCoupon),
      productCateOptions: [],
      selectProduct: null,
      selectProductLoading: false,
      selectProductOptions: [],
      selectProductCate: null,
      productCategoryList: [],
      productList: [],
      productCateOptionsProps: { value: 'id', label: 'label' },
      isEdit: false,
      rules: {
        nameCn: [
          { required: true, message: '中文禮金券名稱不能為空', trigger: 'blur' }
        ],
        nameEn: [
          { required: true, message: '英文禮金券名稱不能為空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.isEdit = this.$route.query.isEdit
    if (this.isEdit) {
      getOne(this.$route.query.id).then(res => {
        const couponData = res.data
        setTitle('修改禮金券:' + couponData.nameCn)
        if (couponData.product instanceof Array) {
          couponData.product.forEach(item => {
            this.productList.push({ id: item.id, productName: item.nameCn })
          })
        }
        if (couponData.productCategory instanceof Array) {
          couponData.productCategory.forEach(item => {
            this.productCategoryList.push({ id: item.id, productCategoryName: item.nameCn })
          })
        }
        delete couponData.product
        delete couponData.productCategory
        this.form = couponData
      })
    }
    getTree().then(res => {
      this.productCateOptions = res.data
    })
  },
  methods: {
    handleAddProductCategoryRelation() {
      if (this.selectProductCate === null || this.selectProductCate.length === 0) {
        this.$message({
          message: '請先選擇商品分類',
          type: 'warning'
        })
        return
      }
      if (this.form.productCategoryIds.indexOf(this.selectProductCate[this.selectProductCate.length - 1]) > -1) {
        this.$message({
          message: '該商品分類已添加',
          type: 'warning'
        })
        return
      }
      this.productCategoryList.push(this.getProductCateByIds(this.selectProductCate))
      this.form.productCategoryIds.push(this.selectProductCate[this.selectProductCate.length - 1])
      this.selectProductCate = []
    },

    getProductCateByIds(ids) {
      let name = ''
      for (let i = 0; i < this.productCateOptions.length; i++) {
        if (this.productCateOptions[i].id === ids[0]) {
          if (this.productCateOptions[i].hasChildren) {
            for (let j = 0; j < this.productCateOptions[i].children.length; j++) {
              if (this.productCateOptions[i].children[j].id === ids[1]) {
                name = this.productCateOptions[i].children[j].label
              }
            }
          }
        }
      }
      return { id: ids[1], productCategoryName: name }
    },
    handleDeleteProductCateRelation(index, row) {
      this.form.productCategoryIds.splice(index, 1)
      this.productCategoryList.splice(index, 1)
    },
    handleAddProductRelation() {
      if (this.selectProduct === null) {
        this.$message({
          message: '請先選擇商品',
          type: 'warning'
        })
        return
      }
      if (this.form.productIds.indexOf(this.selectProduct) > -1) {
        this.$message({
          message: '該商品已經添加',
          type: 'warning'
        })
        return
      }
      this.form.productIds.push(this.selectProduct)
      this.productList.push(this.getProductById(this.selectProduct))
      this.selectProduct = null
    },
    getProductById(id) {
      for (let i = 0; i < this.selectProductOptions.length; i++) {
        if (id === this.selectProductOptions[i].productId) {
          return this.selectProductOptions[i]
        }
      }
      return null
    },
    handleDeleteProductRelation(index, row) {
      this.form.productIds.splice(index, 1)
      this.productList.splice(index, 1)
    },
    searchProductMethod(query) {
      if (query !== '') {
        this.loading = true
        getProduct({ nameCn: query }).then(response => {
          this.loading = false
          const productList = response.data.rows
          this.selectProductOptions = []
          for (let i = 0; i < productList.length; i++) {
            const item = productList[i]
            this.selectProductOptions.push({ productId: item.id, productName: item.nameCn })
          }
        })
      } else {
        this.selectProductOptions = []
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.form = Object.assign({}, defaultCoupon)
      this.productCategoryList = []
      this.productList = []
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.isEdit) {
              edit(this.form).then(response => {
                this.$refs[formName].resetFields()
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            } else {
              add(this.form).then(response => {
                this.$refs[formName].resetFields()
                this.$message({
                  message: '提交成功',
                  type: 'success',
                  duration: 1000
                })
                this.$router.back()
              })
            }
          })
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.couponCard {
  width: 800px;
  margin: 0 auto;
  margin-bottom: 50px;
}

.input-width {
  width: 60%;
}

.dialog-footer {
  width: 200px;
  margin: 0 auto;
}
</style>
